# coding:utf-8
from . import api
from ihome.utils.commons import login_required, upload_image
from flask import g, request, jsonify, current_app, session
from ihome.utils.response_code import RET
from ihome.models import User
from ihome import constants, db


@api.route('/user', methods=['PUT'])
@api.route('/user/auth', methods=['PUT'])
@api.route('/user/avatar', methods=['POST'])
@login_required
def update_user_info():
    # 获取参数
    uid = g.uid
    image_data = request.files.get('avatar')
    data = request.get_json()
    errno = 0
    errmsg = ''
    user = User.query.get(uid)
    if data:
        username = data.get('username', None)
        real_name = data.get('real_name', None)
        id_card = data.get('id_card', None)
        # 更新用户名
        if username:
            try:
                user.name = username
                # 更新session里的用户名
                session['username'] = user.name
                db.session.add(user)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                errno = RET.DBERR
                errmsg = '该用户名已存在，请换个重试'
                # 实名认证
        if real_name and id_card:
            try:
                user.real_name = real_name
                user.id_card = id_card
                db.session.add(user)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                errno = RET.DBERR
                errmsg = '该身份证号已被认证'

    # 更新头像
    if image_data:
        try:
            # 上传图片
            file_name = upload_image(image_data.read())
            # 更新数据库
            user.avatar_url = file_name
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            errno = RET.THIRDERR
            errmsg = '设置头像失败'

    # 返回
    if errno == 0:
        return jsonify(errno=RET.OK, errmsg='设置成功', data={'avatar':user.avatar_url, 'username':user.name})
    else:
        return jsonify(errno=errno, errmsg=errmsg)


@api.route('/user', methods=['GET'])
@login_required
def user_info():
    user = User.query.get(g.uid)
    return jsonify(errno=RET.OK, errmsg='ok', data=user.to_dict())
